package com.sicnu.websocket.rd;

import com.sicnu.websocket.vo.Message;
import com.sicnu.websocket.websocket.InMemoryMessageStore; // 假设路径正确
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class MessageService {

    private java.util.concurrent.atomic.AtomicInteger saveCounter = new java.util.concurrent.atomic.AtomicInteger(0);
    private boolean simulateFailure = true; // 设置为 true 开始模拟失败


    @CircuitBreaker(name = "backendA", fallbackMethod = "saveMessageFallback")
    public void saveMessage(Message message) {
        log.debug("尝试保存消息: {}", message);

        // --- 模拟失败逻辑 (用于测试) ---
        if (simulateFailure && saveCounter.incrementAndGet() % 2 == 0) { // 例如，让一半的调用失败
            log.warn("模拟saveMessage失败 !!!");
            throw new RuntimeException("模拟数据库连接失败");
        }

        log.debug("消息已保存: {}", message);
    }

    public void saveMessageFallback(Message message, Throwable t) {
        log.error("保存消息失败，执行降级逻辑。消息: {}, 错误: {}", message, t.getMessage());

    }


}